package com.yimixian.app.net;

import android.content.Context;
import android.util.Log;

import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.User;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.StringUtils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;

/**
 * 网络管理类（需要可扩展）
 * 
 * @author
 * 
 */
public class NetManager {
	private HttpClient client;
	private Context context;

	public NetManager(Context context) {
		this.context = context;
		client = HttpClientFactory.getHttpClient(context);
	}

	public InputStream HandlerRequest(String method, Map<String, String> map, String urlEncode, HttpApi.RequestMethod requestMethod) {
		if (StringUtils.isNullOrEmpty(method)) {
			return null;
		}
		NetConstants.HTTP_URL = NetConstants.HTTP_SCHEME + "://" + NetConstants.HTTP_HOST;
		if(method.indexOf("http") != -1 || method.indexOf("https") != -1){
			NetConstants.HTTP_URL = method;
		}else{
			method = NetConstants.HTTP_URL + method;
		}

//		if(StringUtils.isNullOrEmpty(httpRequestHead)){
//			method = NetConstants.HTTP_URL + method;
//		}else{
//			if(httpRequestHead.indexOf("http") != -1){
//				method = ("/".equals(httpRequestHead.substring(httpRequestHead.length() - 1)) ? httpRequestHead : httpRequestHead + "/") + method;
//			}else{
//				method = NetConstants.HTTP_SCHEME + "://" + ("/".equals(httpRequestHead.substring(httpRequestHead.length() - 1)) ? httpRequestHead : httpRequestHead + "/") + method;
//			}
//		}

		if(map == null)
			map = new HashMap<>();

		User user = SharedPreferencesHelper.getUser(SharePreferenceKeys.CURRENT_USER);
		if(user != null && user.token != null){
			map.put("token", user.token);
		}
		map.put("refer_from", "APP_ANDROID_" + DataManager.getInstance().get(CacheKeys.VERSION_NAME) + "_" +
				DataManager.getInstance().get(CacheKeys.INSTALL_CHANNEL));

		if (requestMethod == HttpApi.RequestMethod.METHOD_GET) {
			method += buildUrl(map);
			Log.i("url", "url---get---" + method);
			return createGetRequest(method);
		} else {
			return createPostRequest(method, map);
		}
	}

	public InputStream HandlerRequest(String method, Map<String, String> map,int flag, String urlEncode, HttpApi.RequestMethod requestMethod) {
		return HandlerRequest(method, map, urlEncode, requestMethod);
	}

	public InputStream HandlerRequest(String method, Map<String, String> map, HttpApi.RequestMethod requestMethod) {
		return HandlerRequest(method, map, NetConstants.ENCODING, requestMethod);
	}

	public String buildUrl(Map<String, String> map) {
		return buildUrl(map, NetConstants.ENCODING);
	}

	/**
	 * get方式拼接url地址
	 */
	public String buildUrl(Map<String, String> map, String encode) {
		StringBuilder sb = new StringBuilder();
		String value;
		try {
			if (map.size() > 0) {
				sb.append("?");
				for (Entry<String, String> entry : map.entrySet()) {
					value = "";
					value = entry.getValue();
					if(StringUtils.isNullOrEmpty(value))
						value = "";
//					value = URLEncoder.encode(value, encode);
					sb.append(entry.getKey()).append("=").append(value)
							.append("&");
				}
				sb.deleteCharAt(sb.length() - 1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (!StringUtils.isNullOrEmpty(sb.toString())
				|| sb.toString().length() > 0) {
			String str = sb.toString().substring(1, sb.toString().length());
			str = StringUtils.getMD5Str(str + NetConstants.MD);
//			sb.append("&wirelesscode=" + str);
//			sb.append("&imei=" + Apn.imei);
		}
		return sb.toString();
	}

	/**
	 * get方式拼接url地址(新房)
	 */
	public String buildUrl_XF(Map<String, String> map) {
		StringBuilder sb = new StringBuilder();
		String value;
		try {
			if (map.size() > 0) {
				sb.append("?");
				for (Entry<String, String> entry : map.entrySet()) {
					value = "";
					value = entry.getValue();
					if (StringUtils.isNullOrEmpty(value)) {
						continue;
					} else {
						value = URLEncoder.encode(value, NetConstants.ENCODING);
					}
					sb.append(entry.getKey()).append("=").append(value).append("&");
				}
				sb.deleteCharAt(sb.length() - 1);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * post方式封装键值
	 */
	public UrlEncodedFormEntity buildFormEntity(Map<String, String> map) {
		try {
			String value;
			if (map.size() > 0) {
				// String meString = map.get(SoufunConstants.MWSSAGE_NAME);
				// String wirelesscode = StringUtils.getMD5Str(meString + MD);
				// map.put("wirelesscode", wirelesscode);
				List<NameValuePair> list = new ArrayList<NameValuePair>();
				for (Entry<String, String> entry : map.entrySet()) {
					value = "";
					value = entry.getValue();
					if (StringUtils.isNullOrEmpty(value)) {
						continue;
					}
					list.add(new BasicNameValuePair(entry.getKey(), value));

				}
				return new UrlEncodedFormEntity(list, HTTP.UTF_8);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获得Get方式请求
	 *
	 * @param url
	 * @return
	 */
	public InputStream createGetRequest(String url) {
		if (StringUtils.isNullOrEmpty(url))
			return null;
		HttpGet httpGet = new HttpGet(url);
		try {
			for (Entry<String, String> entry : Apn.getHeads().entrySet()) {
				String value = entry.getValue();
				if (!StringUtils.isNullOrEmpty(value)) {
					value = URLEncoder.encode(value, NetConstants.ENCODING);
				}
				httpGet.addHeader(entry.getKey(), value);
//				UtilsLog.e("header", entry.getKey() + " = " + entry.getValue());
			}
			HttpResponse response = client.execute(httpGet);
			switch (response.getStatusLine().getStatusCode()) {
			case HttpStatus.SC_OK:
				return getUngzippedContent(response.getEntity());
			default:
				httpGet.abort();
				return null;
			}
		} catch (Exception e) {
			httpGet.abort();
			e.printStackTrace();
			return null;
		}
	}


	/**
	 * 获得Post方式请求
	 *
	 * @param url
	 * @param map
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public InputStream createPostRequest(String url, Map<String, String> map) {
		if (StringUtils.isNullOrEmpty(url))
			return null;

		HttpPost httpPost = new HttpPost(url);
		Log.i("url", "url---post---" + url + buildUrl(map));
		try {

			for (Entry<String, String> entry : Apn.getHeads().entrySet()) {
				String value = entry.getValue();
				if (!StringUtils.isNullOrEmpty(value)) {
					value = URLEncoder.encode(value, NetConstants.ENCODING);
				}
				httpPost.addHeader(entry.getKey(), value);
			}

			UrlEncodedFormEntity buildFormEntity = buildFormEntity(map);
			if (buildFormEntity != null)
				httpPost.setEntity(buildFormEntity);


		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			HttpResponse response = client.execute(httpPost);
			switch (response.getStatusLine().getStatusCode()) {
			case HttpStatus.SC_OK:
				return getUngzippedContent(response.getEntity());
			default:
				httpPost.abort();
				return null;
			}
		} catch (Exception e) {
			httpPost.abort();
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 判断是否是gzip
	 *
	 * @param entity
	 * @return
	 * @throws IOException
	 */
	public InputStream getUngzippedContent(HttpEntity entity)
			throws IOException {
		InputStream responseStream = entity.getContent();
		if (responseStream == null) {
			return responseStream;
		}
		Header header = entity.getContentEncoding();
		if (header == null) {
			return responseStream;
		}
		String contentEncoding = header.getValue();
		if (contentEncoding == null) {
			return responseStream;
		}
		if (contentEncoding.contains(Apn.HTTP_PRESSED_TYPE)) {
			responseStream = new GZIPInputStream(responseStream);
		}
		return responseStream;
	}

	public String getContentByString(InputStream is) throws IOException {
		if (is == null)
			return null;
		InputStreamReader reader = new InputStreamReader(is, NetConstants.ENCODING);
		BufferedReader br = new BufferedReader(reader);
		StringBuilder sb = new StringBuilder();
		String line = "";
		while ((line = br.readLine()) != null) {
			sb.append(line);
		}
//		UtilsLog.e("sb", sb.toString());
		return sb.toString();
	}

	public void close() {
		try {
			client.getConnectionManager().shutdown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * JSON形式传输
	 *
	 * @param url
	 * @return
	 */
	public InputStream createPostRequestJson(String url, String json) {
		if (StringUtils.isNullOrEmpty(url))
			return null;
		Log.e("url", url);
		HttpPost httpPost = new HttpPost(url);

		try {
			StringEntity requestJson = new StringEntity(json, "UTF-8");
			httpPost.setEntity(requestJson);
			// for (Entry<String, String> entry : Apn.getHeads().entrySet()) {
			// String value = entry.getValue();
			// if (!StringUtils.isNullOrEmpty(value)) {
			// value = URLEncoder.encode(value, ENCODING);
			// }
			// httpPost.addHeader(entry.getKey(), value);
			// // UtilsLog.e("header", entry.getKey() + " = " +
			// entry.getValue());
			// }

		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			HttpResponse response = client.execute(httpPost);
			switch (response.getStatusLine().getStatusCode()) {
			case HttpStatus.SC_OK:
				return getUngzippedContent(response.getEntity());
			default:
				httpPost.abort();
				return null;
			}
		} catch (Exception e) {
			httpPost.abort();
			e.printStackTrace();
			return null;
		}
	}
}
